package com.codinghero.example.longleg;

import java.io.File;
import java.util.Map;

import com.codinghero.util.FileUtils;
import com.codinghero.util.ImageUtils;

public class ResizeImage {

	static final class SIZE {
		static final class SMALL {
			static final int WIDTH = 200 * 2;
			static final int HEIGHT = 150 * 2;
			static final double RATE = (double) WIDTH / (double) HEIGHT;
			static final String FOLDER_PATH = 
					Constant.ORIG.FOLDER_PATH + File.separator + 
					"thumbs" + File.separator + 
					"small";
		}

		static final class MIDDLE {
			static final int WIDTH = 420 * 2;
			static final int HEIGHT = 337 * 2;
			static final double RATE = (double) WIDTH / (double) HEIGHT;
			static final String FOLDER_PATH = 
					Constant.ORIG.FOLDER_PATH + File.separator + 
					"thumbs" + File.separator + 
					"middle";
		}

		
	}
	
	@SuppressWarnings("deprecation")
	private static void resize(File file, File destFile, int destWidth, int destHeight) {
		Map<String, Integer> map = ImageUtils.getSize(file);
		int width = map.get("width");
		int height = map.get("height");
		double rate = (double) width / (double) height;
		double destRate = (double) destWidth / (double) destHeight;
		
		if (width < destWidth || height < destHeight)
			FileUtils.copyFile(file.getPath(), destFile.getPath());
		
		if (width > height) {
			if (rate > destRate) {
				ImageUtils.scaleByHeight(file.getPath(), destFile.getPath(), destHeight);
			} else {
				ImageUtils.scaleByWidth(file.getPath(), destFile.getPath(), destWidth);
			}
		} else {
			ImageUtils.scaleByWidth(file.getPath(), destFile.getPath(), destWidth);
		}
	}
	
	private static void handleInFolder(String folderPath) {
		File rootFolder = new File(folderPath);
		File[] files = rootFolder.listFiles();
		for (File file : files) {
			if (file.isFile() && !file.getName().startsWith("Thumbs.db")) {
				String destFolderPath = 
						folderPath + File.separator + 
						"thumbs" + File.separator + 
						"small"; 
				String destFilePath = 
						destFolderPath + File.separator + 
						FileUtils.getSimpleFileName(file.getPath()) + ".small." + FileUtils.getFileType(file.getPath());
				resize(file, new File(destFilePath), SIZE.SMALL.WIDTH, SIZE.SMALL.HEIGHT);
			} else if (file.isDirectory() && !file.getName().startsWith("thumbs")) {
				handleInFolder(file.getPath());
			} 
		}
	}

	public static void main(String[] args) {
		handleInFolder(Constant.ORIG.FOLDER_PATH);
	}
}
